#include "Sound.h"
#include <assert.h>

CSound* CSound::m_instance=0;

CSound::CSound(void):m_mediaEvent(0), m_mediaControl(0), m_graphBuilder(0), m_addressPlayBackSound(""){}

CSound::~CSound(void)
{
	if(m_mediaEvent!=0)
		m_mediaEvent->Release();
	if(m_mediaControl!=0)
		m_mediaControl->Release();
	if(m_graphBuilder!=0)
		m_graphBuilder->Release();
}

CSound* CSound::getInstance(void)
{
	if(m_instance==0)
		m_instance= new CSound();

	return m_instance;
}
void CSound::close()
{
	delete m_instance;
	m_instance=0;
}


bool CSound::initialise()
{
	//initialise COM
	CoInitialize(0);

	//create the filter graph manager
	HRESULT hr=CoCreateInstance(CLSID_FilterGraph, 0, CLSCTX_INPROC_SERVER, IID_IGraphBuilder, (void**)&m_graphBuilder);
	if(FAILED(hr))
		return false;

	hr=m_graphBuilder->QueryInterface(IID_IMediaControl, (void**)&m_mediaControl);
	if(FAILED(hr))
		return false;

	hr=m_graphBuilder->QueryInterface(IID_IMediaEvent, (void**)&m_mediaEvent);
	if(FAILED(hr))
		return false;

	return true;
}

//add the address of a sound to the vector
void CSound::addSound(int* indexSound, string address)
{
	(*indexSound)=(int)m_addressSoundEffect.size();
	m_addressSoundEffect.push_back(address);
}
	
void CSound::addBackSound(string address)
{
	m_addressPlayBackSound=address;
}

void CSound::playSound(int indexSound)
{
	assert(indexSound>=0);

	PlaySound(m_addressSoundEffect[indexSound].c_str(), 0, SND_ASYNC|SND_NODEFAULT);
}

void CSound::playBackSound()
{
	wchar_t newAddress[256];
	MultiByteToWideChar(CP_ACP, 0, m_addressPlayBackSound.c_str(), -1, newAddress, 256);
	HRESULT hr=m_graphBuilder->RenderFile(newAddress, 0);
	if(SUCCEEDED(hr))
		m_mediaControl->Run();
}